Iterator

An iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. An iterator defined for any collection does not load the entire collection into the memory but loads elements one after the other. Therefore, iterators are useful when the data is too large for the memory. To access elements we can make use of hasNext() to check if there are elements available and next() to print the next element.

object demo {
def main(args: Array[String]) {
val v = Iterator(5, 1, 2, 3, 6, 4)
while(v.hasNext)
println(v.next)
}
}

Examples
object demo {
def main(args: Array[String]) {
//val v = Array(5,1,2,3,6,4)
val v = List(5,1,2,3,6,4)
// defining an iterator
// for a collection
val i = v.iterator
while (i.hasNext)
print(i.next + " ")
}
}
// defining iterator 
val i = Iterator(5, 1, 2, 3, 6, 4) 
/* 
OR 
val v = List(5, 1, 2, 3, 6, 4) 
val i = v.iterator 
*/
// accessing elements using while loop 
while (i.hasNext) 
println(i.next) 

// defining iterator 
val i = Iterator(5, 1, 2, 3, 6, 4) 
/* 
OR 
val v = List(5, 1, 2, 3, 6, 4) 
val i = v.iterator 
*/
// accessing elements using foreach 
i foreach println 
// same as i.foreach(println)


// defining iterator 
val i = Iterator(5, 1, 2, 3, 6, 4) 
/* 
OR 
val v = List(5, 1, 2, 3, 6, 4) 
val i = v.iterator 
*/
// accessing elements using for loop 
for(k <- i) println(k) 

// defining iterator 
val i1 = Iterator(5, 1, 2, 3, 6, 4) 
// calling max function 
println("Maximum: "+ i1.max) 
// redefining iterator 
val i2 = Iterator(5, 1, 2, 3, 6, 4) 
// calling min function 
println("Minimum: "+ i2.min) 

No comments:

Post a Comment